<template>
  <div class="wrapBox">
    <div class="ctrls">
      <el-form
        label-position="right"
        :inline="true"
        class="clearfix"
        ref="queryForm"
        size="small"
        :model="queryParams"
        @submit.native.prevent
      >
        <el-form-item label="年份" style="margin-bottom: 0px">
          <el-date-picker v-model="time" type="year" placeholder="请选择年份" value-format="yyyy"> </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="时间单位" style="margin-bottom: 0px">
          <el-select v-model="queryParams.queryByDateType" style="width: 120px" placeholder="请选择时间单位">
            <el-option v-for="item in queryByDateType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item style="margin-bottom: 0px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="general">
      <div>
        <div class="label"><span class="mx-1">项目数</span></div>
        <div class="number">
          <span> {{ baseInfo['projectCount'] || 0 }} </span><span>个</span>
        </div>
      </div>
      <div>
        <div class="label"><span class="mx-1">已中标</span></div>
        <div class="number">
          <span>{{ baseInfo['winTheBid'] || 0 }}</span
          ><span>个</span>
        </div>
      </div>
      <div>
        <div class="label"><span class="mx-1">已签约</span></div>
        <div class="number">
          <span>{{ baseInfo['haveSigned'] || 0 }}</span
          ><span>个</span>
        </div>
      </div>
      <div>
        <div class="label"><span class="mx-1">待签约</span></div>
        <div class="number">
          <span>{{ baseInfo['pendingSigned'] || 0 }}</span
          ><span>个</span>
        </div>
      </div>
      <div>
        <div class="label"><span class="mx-1">已回款</span></div>
        <div class="number">
          <span>{{ baseInfo['paid'] || 0 }}</span
          ><span>元</span>
        </div>
      </div>
      <div>
        <div class="label"><span class="mx-1">未回款</span></div>
        <div class="number">
          <span>{{ baseInfo['unpaid'] || 0 }}</span
          ><span>元</span>
        </div>
      </div>
    </div>
    <div class="content">
      <div ref="totalItems" v-loading="loading"></div>
      <div ref="contractCount" v-loading="loading"></div>
      <div ref="totalCollection" v-loading="loading"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { analysisProject } from '@/api/biz/index'
import { echartsNullData, filterAnalysisData } from '@/utils/index'
import dayjs from 'dayjs'
export default {
  name: 'ProjectSummary',
  data() {
    return {
      baseInfo: {},
      queryParams: {
        queryByDateType: 'month',
        queryType: '1',
        years: [],
      },
      queryByDateType: [
        {
          label: '月',
          value: 'month',
        },
        {
          label: '年',
          value: 'year',
        },
      ],
      loading: false,
      color: ['#3692fd', '#f59063', '#49efcd', '#facf6a', '#fb627d', '#7cc934', '#b22c2a'],
      time: '',
    }
  },
  watch: {
    time: {
      handler(val) {
        this.queryParams.years = [val]
      },
    },
  },
  mounted() {
    this.time = dayjs().format('YYYY')
    this.$nextTick(() => {
      this.initData()
    })
  },
  methods: {
    initData() {
      this.loading = true
      analysisProject({
        ...this.queryParams,
      })
        .then((res) => {
          this.baseInfo = res.data.projectAnalysis
          this.totalItems(res.data.projectAnalysis.children)
          this.contractCount(res.data.projectAnalysis.children)
          this.totalCollection(res.data.projectAnalysis)

          this.$nextTick(() => {
            this.loading = false
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    totalItems(data = []) {
      const chart = echarts.init(this.$refs.totalItems)
      var emphasisStyle = {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0,0,0,0.3)',
        },
      }
      let xLabel = []
      let yValue = []
      let filterData = {}
      const classify = []
      const seriesList = []
      const config = {
        title: {
          text: '项目数统计',
          textStyle: {
            color: '#606266',
            fontSize: 14,
            fontWeight: 'normal',
          },
          top: 10,
          left: 10,
        },
        color: ['#3692fd', '#facf6a', '#fb627d'],
        legend: {
          data: [],
          left: 'center',
          top: 40,
        },
        xAxis: {
          data: [],
          name: '',
          splitLine: { show: false },
          splitArea: { show: false },
          type: 'category',
          axisTick: {
            alignWithLabel: true,
          },
          axisLine: {
            onZero: true,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '',
            axisLine: { onZero: false },
          },
        ],
        grid: {
          top: 80,
          bottom: 40,
        },
        tooltip: {
          trigger: 'axis',
          valueFormatter: (value) => `${value}个`,
        },
        series: [],
      }

      if (this.queryParams.queryByDateType == 'month') {
        for (let i = 0; i < data.length; i++) {
          classify.push(data[i].dateStr)
          yValue.push([])

          const arr = data[i].children || []
          if (i == data.length - 1) {
            xLabel = []
            arr.map((item, index) => {
              xLabel.push(item.dateStrCN)
            })
          }
          arr.map((item) => {
            yValue[yValue.length - 1].push(`${item.projectCount}`)
          })
        }
        // 数据过滤
        filterData = filterAnalysisData({ xLabel, yValue })
        filterData.yValue.map((item, index) => {
          seriesList.push({
            name: classify[index],
            type: 'bar',
            emphasis: emphasisStyle,
            barMaxWidth: 40,
            data: item,
            label: {
              show: true,
              verticalAlign: 'middle',
              position: 'top',
              color: 'inherit',
              formatter: (obj) => `${obj.value != 0 ? obj.value + '个' : ''}`,
            },
          })
        })
        config.legend.data = classify
        config.series = seriesList
        config.xAxis.data = filterData.xLabel
      } else {
        config.legend.show = false
        let total = 0
        for (let i = 0; i < data.length; i++) {
          xLabel.push(`${data[i].dateStr}年`)
          total += data[i].projectCount * 1
          yValue.push(data[i].projectCount)
        }
        if (total === 0) {
          filterData.xLabel = []
          filterData.yValue = []
        } else {
          filterData.xLabel = xLabel
          filterData.yValue = yValue
        }
        config.series = [
          {
            type: 'bar',
            emphasis: emphasisStyle,
            barMaxWidth: 60,
            data: yValue,
            label: {
              show: true,
              verticalAlign: 'middle',
              position: 'top',
              color: 'inherit',
              formatter: (obj) => `${obj.value}${obj.value != 0 ? '个' : ''}`,
            },
          },
        ]
        config.xAxis.data = filterData.xLabel
      }
      if (!filterData.isNull) {
        chart.setOption(config)
      } else {
        echartsNullData(this.$refs.totalItems, echarts, '项目数统计', this)
      }
    },
    contractCount(data = []) {
      const chart = echarts.init(this.$refs.contractCount)
      var emphasisStyle = {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0,0,0,0.3)',
        },
      }
      let xLabel = []
      let yValue = [[], [], []]
      let filterData = {}
      const classify = ['已中标', '已签约', '待签约']
      const seriesList = []
      const config = {
        title: {
          text: '中标签约数统计',
          textStyle: {
            color: '#606266',
            fontSize: 14,
            fontWeight: 'normal',
          },
          top: 10,
          left: 10,
        },
        color: ['#3692fd', '#facf6a', '#fb627d'],
        legend: {
          data: classify,
          left: 'center',
          top: 40,
        },
        xAxis: {
          data: xLabel,
          name: '',
          splitLine: { show: false },
          splitArea: { show: false },
          type: 'category',
          axisTick: {
            alignWithLabel: true,
          },
          axisLine: {
            onZero: true,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '',
            axisLine: { onZero: false },
          },
        ],
        grid: {
          top: 80,
          bottom: 40,
        },
        tooltip: {
          trigger: 'axis',
          valueFormatter: (value) => `${value}个`,
        },
        series: seriesList,
      }
      if (this.queryParams.queryByDateType == 'month') {
        for (let i = 0; i < data.length; i++) {
          const arr = data[i].children || []
          if (i == data.length - 1) {
            xLabel = []
            xLabel = arr.map((item, index) => item.dateStrCN)
            arr.map((item) => {
              yValue[0].push(item.winTheBid)
              yValue[1].push(item.haveSigned)
              yValue[2].push(item.pendingSigned)
            })
          }
        }
        // 数据过滤
        filterData = filterAnalysisData({ xLabel, yValue })
        filterData.yValue.map((item, index) => {
          seriesList.push({
            name: classify[index],
            type: 'line',
            emphasis: emphasisStyle,
            data: item,
            label: {
              show: true,
              verticalAlign: 'middle',
              position: 'top',
              color: 'inherit',
              formatter: (obj) => `${obj.value != 0 ? obj.value + '个' : ''}`,
            },
          })
        })
        config.legend.data = classify
        config.series = seriesList
      } else {
        for (let i = 0; i < classify.length; i++) {
          yValue.push([])
          seriesList.push({
            name: xLabel[i],
            type: 'bar',
            emphasis: emphasisStyle,
            barMaxWidth: 40,
            data: yValue[i],
            label: {
              show: true,
              verticalAlign: 'middle',
              position: 'top',
              color: 'inherit',
              formatter: (obj) => `${obj.value}${obj.value != 0 ? '个' : ''}`,
            },
          })
        }

        let total = 0
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          xLabel.push(`${item.dateStr}年`)
          yValue[0].push(item.winTheBid)
          yValue[1].push(item.haveSigned)
          yValue[2].push(item.pendingSigned)
          total += item.winTheBid * 1 + item.haveSigned * 1 + item.pendingSigned * 1
        }
        if (total === 0) {
          filterData.yValue = []
          filterData.xLabel = []
        } else {
          filterData.yValue = yValue
          filterData.xLabel = xLabel
        }
      }
      config.xAxis.data = filterData.xLabel
      if (!filterData.isNull) {
        chart.setOption(config)
      } else {
        echartsNullData(this.$refs.contractCount, echarts, '中标签约数统计', this)
      }
    },
    totalCollection(data = {}) {
      const chart = echarts.init(this.$refs.totalCollection)
      const currentData = [
        {
          name: '未回款',
          value: data.unpaid * 1,
        },
        {
          name: '已回款',
          value: data.paid * 1,
        },
      ]

      if (data.unpaid * 1 + data.paid * 1 === 0) {
        echartsNullData(this.$refs.totalCollection, echarts, '回款占比', this)
      } else {
        chart.setOption({
          title: {
            text: '回款占比',
            textStyle: {
              color: '#606266',
              fontSize: 14,
              fontWeight: 'normal',
            },
            top: 10,
            left: 10,
          },
          color: this.color,
          tooltip: {
            trigger: 'item',
            valueFormatter: (value) => `${value}元`,
          },
          legend: {
            top: 80,
            left: 'center',
          },
          parallel: {
            top: 0,
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: '50%',
              data: currentData,
              top: 60,
              label: {
                // d 百分比
                formatter: '{b}{c}',
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        })
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.dispose()
      this.initData()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.queryParams.queryByDateType = 'month'
      this.time = dayjs().format('YYYY')
      this.$nextTick(() => {
        this.initData()
      })
    },
    dispose() {
      echarts.dispose(this.$refs.totalItems)
      echarts.dispose(this.$refs.contractCount)
      echarts.dispose(this.$refs.totalCollection)
    },
  },
}
</script>
<style lang="scss" scoped>
.wrapBox {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.ctrls {
  width: 100%;
  height: 60px;
  padding: 0 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-shrink: 0;
}
.general {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 10px;
  flex-shrink: 0;
  > div {
    width: 15.8%;
    height: 106.67px;
    background: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 15px 5px 15px;
    box-sizing: border-box;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    > .label {
      width: 100%;
      text-align: left;
      font-size: 14px;
      font-weight: 500;
    }
    .number {
      font-size: 24px;
      height: 28px;
      font-weight: 600;
      margin: auto 0;
      line-height: 1;
      display: flex;
      align-items: flex-end;
      justify-content: center;
      > span {
        line-height: 1;
      }
      > span:nth-child(2) {
        display: block;
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 4px;
        margin-left: 4px;
        color: #635f5f;
      }
    }
  }
}
.content {
  display: flex;
  flex-direction: column;
  > div {
    height: 360px;
    margin-top: 10px;
  }
}
</style>
